package com.young.shop_admin.controller;

import com.alibaba.fastjson.JSON;
import com.young.shop_admin.pojo.vo.BaseRespVO;
import com.young.shop_admin.pojo.vo.ManagementCenterDataVO;
import com.young.shop_admin.services.GoodsService;
import com.young.shop_admin.services.ManagementCenterService;
import com.young.shop_admin.services.OrderServices;
import com.young.shop_admin.services.SellerService;
import com.young.shop_admin.services.impl.GoodsServiceImpl;
import com.young.shop_admin.services.impl.ManagementCenterServiceImpl;
import com.young.shop_admin.services.impl.OrderServicesImpl;
import com.young.shop_admin.services.impl.SellerServiceImpl;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

public class BaseController extends HttpServlet {
    protected static OrderServices orderList = new OrderServicesImpl();
    protected static GoodsService goodsList = new GoodsServiceImpl();
    protected static SellerService sellerList = new SellerServiceImpl();
    protected static ManagementCenterService centerData = new ManagementCenterServiceImpl();



    //读取request对象中的参数，装换成指定类型
    protected <T> T convertParamsToEntity(HttpServletRequest req, Class<T> entityClass) {
        StringBuilder jsonStr = new StringBuilder();
        try {
            BufferedReader reader = req.getReader();
            String tempStr;
            while ((tempStr=reader.readLine())!=null) {
                jsonStr.append(tempStr);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        T entity = JSON.parseObject(jsonStr.toString(), entityClass);
        return entity;
    }

    //返回结果转换为输出流
    protected void writerResult(BaseRespVO result, HttpServletResponse resp) {
        String json = JSON.toJSONString(result);
        try {
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void writerSuccessResult(Object data, HttpServletResponse resp) {
        BaseRespVO result = new BaseRespVO<>();
        result.setData(data);
        String json = JSON.toJSONString(result);
        try {
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void writerErrorResult(String errorMsg, HttpServletResponse resp) {
        BaseRespVO result = new BaseRespVO<>();
        result.setCode(BaseRespVO.CodeType.FAILED.getValue());
        result.setMsg(errorMsg);

        String json = JSON.toJSONString(result);
        try {
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
